package io.jee.caisan.weixin.service.security;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.jee.caisan.weixin.domain.SysMember;
import io.jee.caisan.weixin.service.SysMemberService;

@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	private SysMemberService sysMemberService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysMember member = sysMemberService.getSysMemberByUsername(username);
		if (member == null) {
			throw new UsernameNotFoundException("用户名或者密码错误");
		}
		Set<GrantedAuthority> doAuth = new HashSet<>();
		Set<String> authorities = member.getAuthorities();
		for (String authoritie : authorities) {
			doAuth.add(new SimpleGrantedAuthority(authoritie));
		}
		UserInfo userInfo = new UserInfo(member.getUsername(), member.getPassword(), doAuth);
		userInfo.setMid(member.getMid());
		return userInfo;
	}

}
